<style scoped>
.wraper {
    padding: 0 30px;
}

.search {
    padding-bottom: 20px;
}

.search span {
    color: #68777c;
    font-weight: bold;
    padding-right: 18px;
}

.search button {
    background-color: #00a8f7;
    color: #fff;
    margin-left: 8px;
}

.top {
    margin-bottom: 20px;
    border-top: 1px dashed #cccccc;
}

.wraper .headline {
    position: relative;
    font-size: 12px;
    color: #303134;
    font-weight: bold;
    margin: 10px 0;
    line-height: 32px;
    height: 32px;
}

.wraper .add-agent {
    position: absolute;
    top: 0px;
    right: 30px;
    background-color: #348bf2;
    color: #fff;
}

.iconfont {
    font-size: 14px;
}

.red-font {
    color: #ff1f1f;
}

/* 分页 start */

.page {
    margin: 20px 0;
}
.ivu-page {
    padding-bottom: 150px;
} 

/* 分页 end */
.bgred{
    color: #ff4f4f;
    padding-left: 5px;
    padding-right: 5px;
}
.bggreen{
    color: #19be6b;
    padding-left: 5px;
    padding-right: 5px;
}
.mb15{
    margin-bottom: 15px;
}
.mt20{
    margin-top: 20px;
}

</style>
<style>
.nopass{
    color: #ed3f14;
}
.pass{
    color: #19be6b;
}
</style>

<template>
    <div class="employee-manage">
        <product-title></product-title>
        <div class="wraper">
            <div class="detail">
                <!-- <div class="headline">                    
                    <Button class="add-agent" @click='showAdd(-1)'>新增认证码</Button>
                </div> -->
                <div class="pro-con-f">
                    <Row>
                        <Col span="20">
                            <Form ref="" :model="searchForm" inline>
                                <Form-item label="快速搜索：">
                                    
                                </Form-item>
                                <Form-item prop="user">
                                    <Select v-model="searchForm.owner" style="width: 120px;" placeholder="拥有者" filterable>
                                        <Option value="0">全部拥有者</Option>
                                        <Option  :value="item.id" v-for="item in employeelist" :key="item.cid">{{item.name}}</Option>
                                    </Select>
                                </Form-item>
                                <Form-item>
                                    <Select v-model="searchForm.creator" placeholder="生成者"  style="width: 120px;" filterable>
                                        <Option value="0">全部生成者</Option>
                                        <Option  :value="item.id" v-for="item in employeelist" :key="item.cid">{{item.name}}</Option>
                                    </Select>
                                </Form-item>
                                <Form-item>
                                    <Select v-model="searchForm.used" placeholder="使用情况"  style="width: 120px;">
                                        <Option value="0">全部使用情况</Option>
                                        <Option value="1">使用</Option>
                                        <Option value="2">未使用</Option>
                                    </Select>
                                </Form-item>
                                <Form-item>
                                    <Button type="primary" icon="ios-search" @click="getList()">搜索</Button>
                                </Form-item>
                            </Form>
                        </Col>
                        <Col span="4" class="pro-con-fr" v-if="usertype == 1? true : false">
                            <Button type="primary" size="large" @click="showAdd(-1)">新增认证码</Button>
                        </Col>
                        <Col span="4" class="pro-con-fr" v-if="usertype == 2? true : false">
                            <Button type="primary" size="large" @click="showchange(-1)">批量转出</Button>
                        </Col>
                    </Row>
                </div>
                <div class="clearfix">
                    <Row>
                        <Col span="24" class="mb15">
                            可用认证码<span class="bggreen">{{usable}}</span>条，共<span class="bgred">{{Total}}</span>条
                        </Col>
                    </Row>
                    <Table stripe border ref="selection" :columns="columns_rank" :data="data_rank" @on-selection-change="selectionChange($event)"></Table>
                    <Button class="mt20" @click="handleSelectAll(true)" v-if="usertype == 2? true : false">全选</Button>
                    <Button class="mt20" @click="handleSelectAll(false)" v-if="usertype == 2? true : false">取消全选</Button>
                    <Button class="mt20" type="primary" @click="showchange(-1)" v-if="usertype == 2? true : false">批量转出</Button>
                    <Row class="page fr">
                        <Col span="24">
                        <Page :total="Total" show-total show-sizer @on-change="pageChange" @on-page-size-change="pageSizeChange"></Page>
                        </Col>
                    </Row>
                </div>
            </div>
        </div>
        <Modal v-model="showAddModal" :mask-closable='closeable' width="600" title="新增认证码" @on-ok="add" :loading="loading">
            <Row>
                <Col span="18" offset="1">
                <Form :model="invitation" ref="invitation" :rules="ruleValidate" :label-width="120">
                    <FormItem label="代理人：" prop="uid" required>
                        <Select v-model="invitation.uid" style="width:306px" placeholder='请选择代理人'>
                            <Option  :value="item.id" v-for="item in employeelist" :key="item.cid">{{item.name}}</Option>                                
                        </Select>
                    </FormItem> 
                    <Form-item label="认证码数量：" prop="num" required>
                        <Input v-model="invitation.num" placeholder="请输入认证码数量"></Input>
                    </Form-item>                                 
                </Form>
                </Col>
            </Row>
        </Modal>
        <Modal v-model="showchangeModal" :mask-closable='closeable' width="600" title="转让认证码" @on-ok="addchange" :loading="loading">
            <Row>
                <Col span="18" offset="1">
                <Form :model="invitationchange" ref="invitationchange" :rules="ruleValidate1" :label-width="120">
                    <FormItem label="代理人：" prop="goal_uid" required>
                        <Select v-model="invitationchange.goal_uid"  filterable remote :remote-method="remoteMethod1" :loading="loading1" style="width:306px" placeholder='请选择代理人'>
                            <Option v-for="(option, index) in employeelist1" :value="option.id" :key="index">{{option.name}}</Option>                             
                        </Select>
                    </FormItem>                               
                </Form>
                </Col>
            </Row>
        </Modal>
    </div>
</template>

<script>
import productTitle from '../../components/productTitle'
import { getRankList , saveRank , updateRank , delRank  } from '../../api/rank'
import { createInvitation , getInvitationList , getTransfer} from '../../api/invitation'
import { getAllEmployee , getAllOfficial, getUidByName } from '../../api/employee'
export default {
    data() {
        return {
            cou:-1,
            checkModal:false,
            showactionModal:false,
            showchangeModal:false,           
            closeable: false,
            loading: true,
            loading1: false,
            loadingtag:false,
            timeout:{},
            options1: [],
            invitation:{
                num:'',
                uid:''
            },
            invitationchange:{
                goal_uid:'',
                code_id:[]
            },
            searchForm:{
                owner:'0',
                creator:'0',
                used:'0',
                p: 1,
                pagesize: 10,
            },
            Total:0,
            usable:0,
            action: {
                active:[]
            },
            selectitems:[],
            showAddModal: false,
            employeelist:[],
            employeelist1:[],
            columns_rank: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    type: 'index',
                    title:'序号',
                    width: 60,
                    align: 'center',
                },
                {
                    title: '生成者',
                    key: 'creator_name',
                    align: 'center',

                },
                {
                    title: '拥有者',
                    key: 'owner_name',
                    align: 'center',
                },
                {
                    title: '使用者',
                    key: 'user_name',
                    align: 'center',
                },
                {
                    title: '认证码',
                    key: 'code',
                    align: 'center',
                    render: (h, params) => {
                        if(params.row.visibel){
                            return h('div', {
                                props:{
                                    className:"ces"
                                },
                                attrs:{
                                    class:(params.row.user_name == '未使用') ? 'pass' : 'nopass' ,
                                },
                                
                            },params.row.code)
                        }else{
                            return h('div', {
                                props:{
                                    className:"ces"
                                },
                                attrs:{
                                    class:(params.row.user_name == '未使用') ? 'pass' : 'nopass' ,
                                },
                                
                            },(params.row.code ? (params.row.code.slice(0,10)+ new Array(20).join('*') + params.row.code.slice(30)) : '暂无'))
                            
                        }                       
                    }
                },
                {
                    title: '操作',
                    key: 'action',
                    width: 200,
                    align: 'center',
                    render: (h, params) => {
                        return h('div', [
                            (this.usertype == 2 && params.row.user_name == '未使用') ? (h('Button', {
                                props: {
                                    type: 'success',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.showcode(params.index)
                                    }
                                }
                            }, '显示')) : '',
                            (this.usertype == 2 && params.row.user_name == '未使用') ? (h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.showchange(params.row.id)
                                    }
                                }
                            }, '转让')
                            ) : '',
                            (this.usertype == 2 && params.row.user_name == '未使用') ? (h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small',
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.docopy(params.row.code)
                                    }
                                }
                            }, '复制')
                            ) : '',
                        ]);
                    }
                },
            ],
            data_rank: [

            ],
            ruleValidate: {
                num: [
                    { required: true, message: '认证码数量不能为空', trigger: 'blur' }
                ],
                uid: [
                    { required: true, message: '代理人不能为空', trigger: 'change' }
                ],
            },
            ruleValidate1: {
                goal_uid: [
                    { required: true, message: '代理人不能为空', trigger: 'change' }
                ],
            },
        }
    },
    components: {
        productTitle
    },
    computed: {
      usertype(){
          return this.$store.state.user.user_type
      }  
    },
    created() {
        this.getList()
        this.getEmployee()
    },
    methods: {
        docopy(code){
            this.$copyText(code).then(function (e) {
                alert('复制成功！')
            }, function (e) {
                alert('复制失败！')
            })
        },
        selectionChange(selection){
            console.log(selection)
            this.selectitems = []
            let _length = selection.length
            //this.selectitems =
            if(_length > 0){
                for(let i = 0;i<_length;i++){
                    this.selectitems.push(selection[i].id)
                }
            }
            console.log(this.selectitems)
        },
        handleSelectAll (status) {
                this.$refs.selection.selectAll(status);
        },
        getEmployeeName(name){
            let _params = {
                name:name
            }
            new Promise((resolve, reject) => {
                getUidByName(_params).then(response => {
                    console.log(response.data)
                    if (response.data.err == 0) {
                        this.employeelist1 = response.data.data
                    } else {
                        this.$Message.error(response.data.info);
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        //远程搜索代理人
        remoteMethod1(query){
            if (query !== '') {
                    this.loading1 = true; 
                    clearTimeout(this.timeout)                   
                    this.timeout = setTimeout(() => {
                        this.loading1 = false;
                        this.getEmployeeName(query)
                    }, 500);                  
                } else {
                    this.employeelist1 = [];
                }
        },
        //获取代理人列表
        getEmployee(){
            new Promise((resolve, reject) => {
                getAllOfficial().then(response => {
                    console.log(response.data)
                    if (response.data.err == 0) {
                        this.employeelist = response.data.data
                    } else {
                        this.$Message.error(response.data.info);
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        // 页码改变
        pageChange(page){
            this.searchForm.p = page
            this.getList()
        },
        // 每页条数改变
        pageSizeChange(pagesize){
            this.searchForm.pagesize = pagesize
            this.getList();
        },
        // 搜索
        search() {
            this.getList();
        },
        // 获取验证码列表
        getList() { 
            new Promise((resolve, reject) => {
                getInvitationList(this.searchForm).then(response => {
                    console.log(response.data);
                    if (response.data.err == 0) {
                        this.data_rank = response.data.data.list
                        this.Total = response.data.data.total
                        this.usable = response.data.data.usable
                    } else {
                        this.$Message.error(response.data.info);
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },    
        add() {
            this.$refs['invitation'].validate((valid) => {
                if (valid) {
                    
                    if(this.cou == -1){                        
                        new Promise((resolve, reject) => {
                            createInvitation(this.invitation).then(response => {
                                if (response.data.err == 0) {
                                    this.showAddModal = false;
                                    this.loading = true;
                                    this.getList();
                                    this.$refs['invitation'].resetFields();
                                    this.$Message.success(response.data.info);
                                } else {
                                    this.$Message.error(response.data.info);
                                    setTimeout(() => {
                                        this.loading = false;
                                        this.$nextTick(() => {
                                            this.loading = true;
                                        });
                                    }, 2000);
                                }
                                resolve();
                            }).catch(error => {
                                reject(error);
                            });
                        });
                    }                  
                } else {
                    // 通过loading来阻止modal隐藏，然后手动修改loading来重置确定按钮
                    setTimeout(() => {
                        this.loading = false;
                        this.$nextTick(() => {
                            this.loading = true;
                        });
                    }, 2000);
                }
            })
        },
        showchange(code){
            this.showchangeModal = !this.showchangeModal
            if(code != -1){
                this.invitationchange.code_id = []
                this.invitationchange.code_id.push(code)
                console.log(this.invitationchange.code_id)
            }else{
                this.invitationchange.code_id = []
                this.invitationchange.code_id = this.selectitems
                console.log(this.invitationchange.code_id)
            }
            
        },
        addchange(){
            this.$refs['invitationchange'].validate((valid) => {
                if (valid) { 
                    let _length = this.invitationchange.code_id.length
                    this.$Modal.confirm({
                        title: '转出确认',
                        content: '<p>确认转出'+_length+'条认证码？</p>',
                        onOk: () => {
                            new Promise((resolve, reject) => {
                                getTransfer(this.invitationchange).then(response => {
                                    if (response.data.err == 0) {
                                        this.showchangeModal = false;
                                        this.loading = true;
                                        this.getList();
                                        //this.$Message.success(response.data.info);
                                        setTimeout(() => {
                                            this.$Modal.success({
                                                title: '转出成功',
                                                content: response.data.info,
                                            });
                                        }, 500);
                                    } else {
                                        this.$Message.error(response.data.info);
                                        setTimeout(() => {
                                            this.loading = false;
                                            this.$nextTick(() => {
                                                this.loading = true;
                                            });
                                        }, 2000);
                                    }
                                    resolve();
                                }).catch(error => {
                                    reject(error);
                                });
                            });
                        },
                        onCancel: () => {
                            setTimeout(() => {
                                this.loading = false;
                                this.$nextTick(() => {
                                    this.loading = true;
                                });
                            }, 500);
                        }
                    });                   
                                      
                } else {
                    // 通过loading来阻止modal隐藏，然后手动修改loading来重置确定按钮
                    setTimeout(() => {
                        this.loading = false;
                        this.$nextTick(() => {
                            this.loading = true;
                        });
                    }, 2000);
                }
            })
        },
        transfer(){
            // if(this.selectitems.length > 0){
            //     new Promise((resolve, reject) => {
            //             getTransfer(this.selectitems).then(response => {
            //                 if (response.data.err == 0) {
            //                     this.showchangeModal = false;
            //                     this.loading = true;
            //                     this.getList();
            //                     this.$Message.success(response.data.info);
            //                 } else {
            //                     this.$Message.error(response.data.info);
            //                 }
            //                 resolve();
            //             }).catch(error => {
            //                 reject(error);
            //             });
            //         });
            // }else{
            //     this.$Message.error("请勾选要转移的认证码");
            // }
        },
        showcode(index){
            this.$set(this.data_rank[index],"visibel",true)
        },
        showAdd(){
            this.showAddModal = !this.showAddModal;
        }
    }
}
</script>
